package v1

import (
	"encoding/json"
	"gin-swagger-demo/pkg/app"
	"gin-swagger-demo/pkg/e"
	"gin-swagger-demo/service/es_service"
	"github.com/gin-gonic/gin"
	"github.com/olivere/elastic/v7"
	"net/http"
)

func CreateIndex(c *gin.Context)  {
	appG := app.Gin{C:c}
	err := es_service.CreateIndex(c,"test-wg")
	if err != nil {
		appG.Response(http.StatusOK, e.ERROR, err)
		return
	}
	appG.Response(http.StatusOK, e.SUCCESS, nil)
}


func DelIndex(c *gin.Context)  {
	appG := app.Gin{C:c}
	err := es_service.DeleteIndex(c,"test-wg")
	if err != nil {
		appG.Response(http.StatusOK, e.ERROR, err)
		return
	}
	appG.Response(http.StatusOK, e.SUCCESS, nil)
}

func CreateDoc(c *gin.Context) {
	appG := app.Gin{C:c}
	// 定义数据结构体
	type Data struct {
		Id   string `json:"id"`
		Name string `json:"name"`
		Age  int    `json:"age"`
	}
	data := &Data{
		Id: "111",
		Name: "老鸣",
		Age: 50,
	}
	jsonData,_ := json.Marshal(data)
	err := es_service.Create(c,"test-wg",string(jsonData))
	if err != nil {
		appG.Response(http.StatusOK, e.ERROR, nil)
		return
	}
	appG.Response(http.StatusOK, e.SUCCESS, nil)
}

func Search(c *gin.Context) {
	appG := app.Gin{C:c}
	// 定义数据结构体
	//termQuery := elastic.NewTermQuery("name", "小明")
	//matchQuery := elastic.NewMatchQuery("name", "鸣")
	rangeQuery := elastic.NewRangeQuery("age").Gte(18).Lte(35)
	res,err := es_service.GetByQuery(c,"test-wg",rangeQuery)
	if err != nil {
		appG.Response(http.StatusOK, e.ERROR, nil)
		return
	}
	appG.Response(http.StatusOK, e.SUCCESS, res)
}